package drds.binlog.parse.driver.packets.server;

import drds.binlog.common.Authors;
import drds.binlog.parse.driver.packets.PacketWithHeaderPacket;
import drds.binlog.parse.driver.utils.Bytes;
import drds.common.Author;
import lombok.Getter;
import lombok.Setter;

import java.io.IOException;

@Author(name = Authors.LI_YANG)
public class ErrorPacket extends PacketWithHeaderPacket
{

    @Setter
    @Getter
    public byte fieldCount;
    @Setter
    @Getter
    public int errorNumber;
    @Setter
    @Getter
    public byte sqlStateMarker;
    @Setter
    @Getter
    public byte[] sqlState;
    @Setter
    @Getter
    public String message;

    /**
     * <pre>
     * VERSION 4.1
     *  Bytes                       Name
     *  -----                       ----
     *  1                           field_count, always = 0xff
     *  2                           errno
     *  1                           (sqlstate marker), always '#'
     *  5                           sqlstate (5 characters)
     *  n                           message
     *
     * </pre>
     */
    public void fromBytes(byte[] bytes)
    {
        int index = 0;
        // 1. read field count
        this.fieldCount = bytes[0];
        index++;

        // 2. read error no.
        this.errorNumber = Bytes.readUnsigned2IntLittleEndian(bytes, index);
        index += 2;

        // 3. read marker
        this.sqlStateMarker = bytes[index];
        index++;

        // 4. read sqlState
        this.sqlState = Bytes.readFixedLengthBytes(bytes, index, 5);//!=2348
        index += 5;

        // 5. read message
        this.message = new String(Bytes.readFixedLengthBytes(bytes, index, bytes.length - index));
        //to left of all
        // end read
    }

    public byte[] toBytes() throws IOException
    {
        return null;
    }


}
